package com.meow_woof.service.impl;

import com.meow_woof.dto.GoodsSalesDTO;
import com.meow_woof.entity.Orders;
import com.meow_woof.mapper.OrderMapper;
import com.meow_woof.mapper.UserMapper;
import com.meow_woof.service.ReportService;
import com.meow_woof.service.WorkspaceService;
import com.meow_woof.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;


    private List<LocalDate> localDateList(LocalDate begin,LocalDate end){
        //存放从begin到end之间的每天对应的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //存放每天的营业额
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate date:localDateList(begin, end)){
            //查询date日期对应的营业额数据：状态为已完成的订单金额合计
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(date,LocalTime.MAX);
            //select sum(amount) from orders where order_time>beginTime and order_time<endTime and status=5
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover =orderMapper.sumByMap(map);
            turnover =turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(localDateList(begin, end),","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build() ;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //存放每天新增的用户数量
        //select count(u.id) from user u left join orders o on u.id=o.user_id where create_time < end and create_time > begin
        List<Integer> newUserList = new ArrayList<>();
        //存放每天的总用户数量
        //select count(user_id) from orders where order_time < end and order_time > begin
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : localDateList(begin, end)) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            //总用户数量
            Integer totalUser = orderMapper.countByMap(map);
            totalUserList.add(totalUser);

            //新增用户数
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);

        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(localDateList(begin, end), ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {


        List<Integer> orderCountList =new ArrayList<>();
        List<Integer> validOrderList=new ArrayList<>();

        for (LocalDate date:localDateList(begin, end)){
            LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endtime=LocalDateTime.of(date,LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endtime);
            orderCountList.add(orderMapper.countOrderByMap(map));
            map.put("status",Orders.COMPLETED);
            validOrderList.add(orderMapper.countOrderByMap(map));

        }
        //计算时间区间内的订单总数量
        Integer totalOrderCount =orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate= totalOrderCount==0?0.0:validOrderCount.doubleValue()/totalOrderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDateList(begin, end),","))
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(validOrderCount)
                .orderCountList(StringUtils.join(orderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCountList(StringUtils.join(validOrderList,","))
                .build();
    }

    /**
     * 销量排行top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end,LocalTime.MAX);
        List<GoodsSalesDTO> list=orderMapper.getTop10(beginTime,endTime,Orders.COMPLETED);
        List<String> names=list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers=list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }

    /**
     * 导出excel报表
     *
     * @param response
     */
    public void export(HttpServletResponse response) throws IOException {
    LocalDateTime beginTime = LocalDateTime.of(LocalDate.now().minusDays(30), LocalTime.MIN);
    LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
    BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);

    InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

    if (in == null) {
        throw new IOException("无法找到模板文件: template/运营数据报表模板.xlsx");
    }

    try (XSSFWorkbook excel = new XSSFWorkbook(in);
         ServletOutputStream out = response.getOutputStream()) {

        Sheet sheet = excel.getSheet("Sheet1");
        sheet.getRow(1).getCell(1).setCellValue(beginTime+"-"+endTime);
        sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
        sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
        sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
        for (int i=0;i<30;i++){
            beginTime=LocalDateTime.of(LocalDate.now().minusDays(30-i),LocalTime.MIN);
            endTime=LocalDateTime.of(LocalDate.now().minusDays(30-i),LocalTime.MAX);
            BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
            Row row= sheet.getRow(7+i);
            row.getCell(1).setCellValue(LocalDate.now().minusDays(30-i).toString());
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }
        // 写入响应
        excel.write(out);
    }
}

}
